//
//  TcpClient.c
//  ThreadPool
//
//  Copyright © 2022 sinosun. All rights reserved.
//

#include "TcpClient.h"
#include <arpa/inet.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int createClient()
{
    int ret = -1;
    // 1. 创建通信的套接字
    int nfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == nfd) {
        return ret;
    }
    
    // 2. 绑定本地端口
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(9999); // 大端端口
    // 将主机字节序的点分十进制的IP字符串转成大端的IP地址
    inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr.s_addr);
    

    ret = connect(nfd, (struct sockaddr *)&addr, sizeof(addr));
    if (-1 == ret) {
        perror("connect");
        exit(0);
    }
    
    // 3. 通信
    int number = 0;
    while (1) {
        // 发送数据
        char buffer[1024] = {0,};
        sprintf(buffer, "这是客户端发送了 %d... \n", number++);
        send(nfd, buffer, strlen(buffer) + 1, 0);
        
        // 将buffer清空
        memset(buffer, 0, sizeof(buffer));
        // 接收数据
        int len = recv(nfd, buffer, sizeof(buffer), 0);
        if (len > 0) {
            printf("server say: %s \n", buffer);
            
        }else if (0 == len) {
            perror("服务端已经断开了连接");
            break;
        }
        else{
            perror("recv");
            break;
        }
        
        sleep(5);
    }
    
    // 5. 关闭文件描述符
    close(nfd);
    return 0;
}
